<template>
  <el-container style="height: 100vh;">
    <!-- 左侧：上传 + sheet切换 + 表格 -->
    <el-aside width="45%" style="padding: 10px;">
      <el-card shadow="hover" class="mb-4">
        <h3>上传 Excel 文件</h3>
        <el-upload
          drag
          :show-file-list="false"
          accept=".xlsx,.xls"
          :before-upload="beforeUpload"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
        </el-upload>
        
        <!-- Sheet切换标签栏：标签名后默认添加「月」字 -->
        <el-tabs 
          v-if="sheetNames.length > 0" 
          v-model="activeSheetName" 
          @tab-change="handleSheetChange"
          style="margin-top: 15px;"
          type="card"
        >
          <el-tab-pane 
            v-for="name in sheetNames" 
            :key="name" 
            :label="`${name}月`"
            :name="name"
          ></el-tab-pane>
        </el-tabs>
      </el-card>

      <el-card v-if="tableData.length" shadow="hover" style="max-height: calc(100% - 150px); overflow: auto;">
        <h3>数据预览与编辑</h3>
        <el-table :data="tableData" border height="550">
          <el-table-column
            v-for="(col, index) in columns"
            :key="index"
            :prop="col"
            :label="col"
            align="center"
          >
            <template #default="scope">
              <el-input v-model="scope.row[col]" size="small" />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-aside>

    <!-- 右侧：图表 -->
    <el-main>
      <el-card shadow="hover" style="height: 100%;">
        <div class="echartEdit" v-if="tableData.length">
          <div>
            <div>
              <span>X轴文字：</span>
              <el-input v-model="xText" style="width: 120px;margin-right: 5px;"></el-input>
              
              <el-color-picker
                v-model="xAxisColor"
                size="small"
                :predefine="predefinedColors"
              ></el-color-picker>
            </div>
            <div>
              <span>Y轴文字：</span>
              <el-input v-model="yText" style="width: 120px;margin-right: 5px;"></el-input>
              
              <el-color-picker
                v-model="yAxisColor"
                size="small"
                :predefine="predefinedColors"
              ></el-color-picker>
            </div>
            <!-- 新增：grid top属性设置 -->
            <div>
              <span>图例距离：</span>
              <el-input 
                v-model.number="gridTop" 
                style="width: 50px;margin-right: 5px;"
                placeholder="默认自动计算"
              ></el-input>
              <span>px</span>
            </div>
          </div>
          
          <!-- 颜色+线型设置区域（优化核心） -->
          <div class="color-settings">
            <div v-for="(item, index) in seriesStyleSettings" :key="index" class="color-item">
              <el-checkbox v-model="item.visible" size="small"></el-checkbox>
              <span>{{ baseoptions?.featureCols[index] || `系列${index+1}` }}</span>
              
              <!-- 颜色选择器 -->
              <el-color-picker
                v-model="item.color"
                size="small"
                :predefine="predefinedColors"
              ></el-color-picker>
              
              <!-- 新增：线型选择器 @change="generateChart" -->
              <el-select
                v-model="item.lineType"
                size="small"
                style="width: 80px;"
              >
                <el-option label="实线" value="solid"></el-option>
                <el-option label="虚线" value="dashed"></el-option>
                <el-option label="点线" value="dotted"></el-option>
              </el-select>
            </div>
          </div>
          
          <div class="button-group">
            <el-button type="primary" @click="generateChart">生成廓线图</el-button>
            <el-button type="primary" @click="exportChartAsImage">导出为图片</el-button>
          </div>
        </div>
        <div ref="chartRef" style="width: 550px; height: 650px;margin-left: 20%;"></div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import * as XLSX from "xlsx";
import * as echarts from "echarts";
import { ref, nextTick } from "vue";
import { ElMessage } from "element-plus";

const yText = ref("");
const xText = ref("");
// 新增：轴颜色设置，默认为黑色
const xAxisColor = ref('#000000');
const yAxisColor = ref('#000000');
// 新增：grid top属性设置
const gridTop = ref(null);

const tableData = ref([]);
const columns = ref([]);
const chartRef = ref(null);
let chartInstance = null;

// 新增：多sheet相关状态
const sheetNames = ref([]); // 存储所有sheet名称
const activeSheetName = ref(""); // 当前激活的sheet名称
const allSheetData = ref({}); // 存储所有sheet的数据，格式：{ sheetName: { data: [], columns: [] } }
const excelFileName = ref(""); // 存储Excel文件名（用于默认X轴文字）

// 颜色相关配置
const predefinedColors = [
  '#4a7ebb','#be4b48','#98b954','#7d60a0','#FF0000', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF','#FF6600', 
  '#0066FF', '#6600FF', '#FF0066', '#00FF66', '#00FF00','#66FF00'
];

// 优化核心：合并系列样式配置（可见性、颜色、线型）
const seriesStyleSettings = ref([]); // 结构：[{ visible: boolean, color: string, lineType: string }]

// 上传前验证
function beforeUpload(file) {
  const isExcel = file.name.endsWith(".xls") || file.name.endsWith(".xlsx");
  if (!isExcel) {
    ElMessage.error("请上传 Excel 文件");
    return false;
  }
  readExcel(file, file.name);
  return false;
}

// 读取 Excel 文件（支持多sheet）
function readExcel(file, fileName) {
  const reader = new FileReader();
  reader.onload = (e) => {
    gridTop.value = null;
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    
    // 存储所有sheet名称
    sheetNames.value = workbook.SheetNames;
    // 存储Excel文件名（用于默认X轴文字）
    excelFileName.value = fileName.replace(/\.(xlsx|xls)$/i, '');
    
    // 读取所有sheet的数据并存储
    allSheetData.value = {};
    sheetNames.value.forEach(sheetName => {
      const sheet = workbook.Sheets[sheetName];
      let json = XLSX.utils.sheet_to_json(sheet);
      // 过滤掉相关系数行
      json = json.filter(item => item['月份'] != "相关系数");
      
      if (json.length) {
        const cols = Object.keys(json[0]).filter(item => item.indexOf("标准差") == -1);
        allSheetData.value[sheetName] = {
          data: json,
          columns: cols
        };
      } else {
        allSheetData.value[sheetName] = {
          data: [],
          columns: []
        };
        // 提示信息也添加「月」字
        ElMessage.warning(`Sheet "${sheetName}月" 为空`);
      }
    });
    
    // 激活第一个sheet
    if (sheetNames.value.length > 0) {
      activeSheetName.value = sheetNames.value[0];
      // 加载第一个sheet的数据
      loadSheetData(activeSheetName.value);
    }
    
    ElMessage.success(`Excel 文件读取成功！共发现 ${sheetNames.value.length} 个工作表`);
  };
  reader.readAsArrayBuffer(file);
}

// 加载指定sheet的数据
function loadSheetData(sheetName) {
  const sheetInfo = allSheetData.value[sheetName];
  if (!sheetInfo) return;
  
  tableData.value = sheetInfo.data;
  columns.value = sheetInfo.columns;
  
  // 初始化X轴文字（文件名 + sheet名 + 月），保持与标签一致
  xText.value = `${excelFileName.value}_${sheetName}月`;
  
  // 初始化Y轴文字（第二列）
  if (columns.value.length >= 2) {
    yText.value = columns.value[1];
  } else {
    yText.value = "";
  }
  
  // 初始化系列样式配置（可见性+颜色+线型）
  const featureCols = columns.value.slice(2);
  seriesStyleSettings.value = featureCols.map((_, index) => ({
    visible: true, // 默认可见
    color: predefinedColors[index % predefinedColors.length], // 默认颜色
    lineType: index > 1 ? 'dashed' : 'solid' // 默认实线
  }));
  
  // 生成图表
  if (tableData.value.length) {
    generateChart();
  } else {
    // 清空图表
    if (chartInstance) {
      chartInstance.clear();
    }
  }
}

// 处理sheet切换
function handleSheetChange(sheetName) {
  loadSheetData(sheetName);
}

let baseoptions = null;

// 绘制廓线图
function generateChart() {
  if (!tableData.value.length) {
    // 提示信息添加「月」字
    ElMessage.warning(`当前工作表"${activeSheetName.value}月"无有效数据`);
    return;
  }
  
  // 第二列作为 Y 轴（例如：大地高）
  const yCol = columns.value[1];
  const featureCols = columns.value.slice(2);

  const yData = tableData.value.map((row) => Number(row[yCol]));
  const series = featureCols.map((col, index) => {
    const style = seriesStyleSettings.value[index];
    return {
      name: col,
      type: "line",
      smooth: true,
      showSymbol: false,
      show: style.visible, // 控制可见性
      lineStyle: {
        color: style.color, // 控制颜色
        type: style.lineType, // 控制线型（新增核心）
        width: 2 // 线条宽度（优化视觉效果）
      },
      data: tableData.value.map((row) => [Number(row[col]), Number(row[yCol])]),
    };
  });
  
  baseoptions = { series, featureCols };
  if (baseoptions.series.filter(item => item.show).length === 0) {
    ElMessage.warning("至少选择1个要素");
  }
  drawChart();
}

function drawChart() {
  nextTick(() => {
    if (!chartInstance) {
      chartInstance = echarts.init(chartRef.value);
      // 监听窗口大小变化，自动调整图表
      window.addEventListener('resize', () => {
        chartInstance.resize();
      });
    } else {
      chartInstance.clear(); // 清空已有图表
    }
    
    // 计算 X 轴范围（带缓冲）
    let xMin = Infinity;
    let xMax = -Infinity;
    baseoptions.series.forEach(series => {
      if (series.show) {
        series.data.forEach(([xVal]) => {
          if(xVal && !isNaN(xVal)){
            xMin = Math.min(xMin, xVal);
            xMax = Math.max(xMax, xVal);
          }
        });
      }
    });
    const buffer = (xMax - xMin) * 0.01;
    const adjustedMin = Math.floor(xMin - buffer);
    const adjustedMax = Math.ceil(xMax + buffer);

    // 计算 Y 轴范围（带缓冲）
    let yMin = Infinity;
    let yMax = -Infinity;
    baseoptions.series.forEach(series => {
      if (series.show) {
        series.data.forEach(([_, yVal]) => {
          if(yVal && !isNaN(yVal)){
            yMin = Math.min(yMin, yVal);
            yMax = Math.max(yMax, yVal);
          }
        });
      }
    });
    const yBuffer = (yMax - yMin) * 0.05;
    const adjustedYMin = Math.floor(yMin - yBuffer);
    const adjustedYMax = Math.ceil(yMax + yBuffer);
    console.dir("baseoptions.series");
    console.dir(baseoptions.series);
    // 准备图例数据和颜色
    const legendData = baseoptions.featureCols.filter((_, index) => 
      seriesStyleSettings.value[index].visible
    );
    const legendColors = baseoptions.featureCols.map((_, index) => 
      seriesStyleSettings.value[index].color
    );

    // 计算 grid top 值
    if (!gridTop.value) {
      gridTop.value = Math.ceil(legendData.length / 4) * 35;
    }
    const calculatedGridTop = gridTop.value;
    
    const option = {
      backgroundColor: "#fff",
      tooltip: { 
        trigger: "axis",
        formatter: function(params) {
          let res = `${params[0].name}<br/>`;
          params.forEach(item => {
            res += `<span style="display:inline-block;width:10px;height:2px;background-color:${item.color};margin-right:5px;"></span>`;
            res += `${item.seriesName}: ${item.value[0].toFixed(2)}, ${item.value[1].toFixed(0)}<br/>`;
          });
          return res;
        }
      },
      legend: {
        data: legendData,
        top: 10,
        left: 90,
        icon: 'rect',
        itemWidth: 15,
        itemHeight: 2,
        itemGap: 5,
        padding: [0, 10, 0, 0],
        textStyle: {
          color: function(params) {
            const index = baseoptions.featureCols.indexOf(params.name);
            return legendColors[index] || '#000';
          },
          fontSize: 16
        },
      },
      grid: { 
        left: 70, 
        right: 30, 
        top: calculatedGridTop,
        bottom: 50,
        show: true, 
        borderColor: "#000",
        borderWidth: 1
      },
      xAxis: {
        type: "value",
        name: xText.value,
        nameLocation: "middle",
        nameGap: 25,
        axisLine: { lineStyle: { color: "#333" }, onZero: false },
        splitLine: { show: false },
        axisLabel: {
            fontSize: 16,
            color: '#000'
        },
        nameTextStyle:{
           fontSize: 16,
           color: xAxisColor.value
        },
        min: adjustedMin,
        max: adjustedMax,
        boundaryGap: false
      },
      yAxis: {
        type: "value",
        name: yText.value,
        nameLocation: "middle",
        nameGap: 40,
        inverse: false,
        axisLine: { lineStyle: { color: "#333" }, onZero: false },
        splitLine: { show: false },
        axisLabel: {
            fontSize: 16,
            color: '#000'
        },
        nameTextStyle:{
           fontSize: 16,
           color: yAxisColor.value
        },
        splitNumber: 15
      },
      series: baseoptions.series.filter(item => item.show).map((series, index) => {
        const styleIndex = baseoptions.featureCols.indexOf(series.name);
        const style = seriesStyleSettings.value[styleIndex];
        return {
          ...series,
          color: style.color,
          lineStyle: {
            color: style.color,
            type: style.lineType, // 应用线型设置
            width: 2
          }
        };
      }),
    };
    
    chartInstance.setOption(option);
  });
}

// 导出图像功能
function exportChartAsImage() {
  if (!chartInstance) return;
  const img = chartInstance.getDataURL({
    type: "png",
    pixelRatio: 2, // 提高图片分辨率
    backgroundColor: "#fff",
  });

  const link = document.createElement("a");
  link.href = img;
  // 文件名包含带「月」字的sheet名称，保持一致性
  link.download = `${excelFileName.value}_${activeSheetName.value}月.png`;
  link.click();
  ElMessage.success("已导出图像！");
}
</script>

<style>
.el-table .cell{
  padding: 0px 2px;
}
.el-main{
  padding: 10px;
}
.el-select__placeholder{
    font-size: 14px;
    color: #000;
}
.upload-demo {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  text-align: center;
  padding: 30px 0;
}
.mb-4 {
  margin-bottom: 1rem;
}
.echartEdit {
  position: relative;
  flex-direction: column;
  margin-bottom: 5px;
}
.echartEdit > div:first-child {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}
.echartEdit > div:first-child > div {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.echartEdit > div:first-child span {
  display: block;
  margin-right: 5px;
}
.color-settings {
  display: flex;
  gap: 5px; /* 增加间距，避免拥挤 */
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
  min-height: 30px;
  padding: 5px 0;
  border-top: 1px solid #eee; /* 增加分隔线，优化布局 */
}
.color-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0;
  margin-right: 20px;
}
/* 优化复选框和文字对齐 */
.color-item .el-checkbox {
  display: flex;
  align-items: center;
}
.button-group {
  display: flex;
  gap: 10px;
  right: 20px;
  top: 0;
  position: absolute;
}
/* 响应式优化：小屏幕时按钮组换行 */
@media (max-width: 1200px) {
  .button-group {
    position: static;
    margin-top: 10px;
  }
  .color-settings {
    gap: 15px;
  }
}
/* 优化sheet标签样式 */
.el-tabs--card > .el-tabs__header .el-tabs__nav {
  border-bottom: none;
}
.el-tabs--card > .el-tabs__header .el-tabs__item {
  border-bottom: 1px solid #e4e7ed;
}
.el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
  border-bottom-color: #409eff;
}
</style>